package club.xcgame520.picturepicker;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.github.chrisbanes.photoview.PhotoView;
import club.xcgame520.picturepicker.bean.Picture;

public class PictureLookActivity extends AppCompatActivity implements View.OnClickListener {

    private Picture picture;

    private Toolbar tTitle;
    private TextView tvComplete;

    private ProgressBar pbLoad;
    private PhotoView pvPicture;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture_look);

        if (savedInstanceState == null) {
            picture = (Picture) getIntent().getSerializableExtra("picture");
        } else {
            picture = (Picture) savedInstanceState.getSerializable("picture");
        }

        tTitle = findViewById(R.id.tTitle);
        setSupportActionBar(tTitle);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        tTitle.setNavigationIcon(R.drawable.vector_action_back);
        tvComplete = findViewById(R.id.tvComplete);
        tvComplete.setOnClickListener(this);

        pbLoad = findViewById(R.id.pbLoad);
        pvPicture = findViewById(R.id.pvPicture);

        Glide.with(this)
                .load(picture.getPath())
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        pbLoad.setVisibility(View.GONE);
                        pvPicture.setImageDrawable(resource);
                    }
                });

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putSerializable("picture", picture);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tvComplete) {
            Intent intent = getIntent();
            intent.putExtra("picture", picture);
            setResult(RESULT_OK, intent);
            finish();
        }
    }
}
